package cn.xu.bookstore.book.web.servlet.admin;


import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.itcast.commons.CommonUtils;
import cn.xu.bookstore.book.domain.Book;
import cn.xu.bookstore.book.service.BookService;
import cn.xu.bookstore.category.domain.Category;
import cn.xu.bookstore.category.service.CategoryService;

public class AdminAddBookServlet extends HttpServlet {
	
	private BookService bookService = new BookService();
	private CategoryService categoryService = new CategoryService();
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/*
		 * 设置 编码格式
		 */
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		/*
		 * 创建工厂 来解析表单中的条目
		 * 通过工厂来得到 服务器文件上传解析器
		 * 通过解析器来解析 请求头 并得到 上传的所有条目
		 * 
		 * 
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory); 
		//设置单个文件的大小 20kb
		fileUpload.setFileSizeMax(20*1024);
		try {
			List<FileItem> fileItems = fileUpload.parseRequest(request);
			/*
			 * 将条目进行分类管理
			 * 如果是一般文件则 刚到一Map中并使用工具一键封装成Book对象
			 */
			Map<String,Object> map = new HashMap<String, Object>();
			for(FileItem fileItem : fileItems){
				if(fileItem.isFormField()){
					String name = fileItem.getFieldName();//表单中的input名字
					String value = fileItem.getString("utf-8");//以这种编码来解析name的值以防止乱码
					map.put(name,value);
				}
			}
			
			/*
			 * 封装成javabean,并设置bid
			 * category ,del
			 */
			Book book = CommonUtils.toBean(map, Book.class);
			book.setBid(CommonUtils.uuid());
			Category category = CommonUtils.toBean(map, Category.class);
			book.setCategory(category);
			book.setDel(false);
			/*
			 * 对图片的操作
			 * 图片这一项在 表单中的第二项1
			 */
			FileItem file_image = fileItems.get(1);
			String image_name = CommonUtils.uuid()+"_"+file_image.getName();
			book.setImage("book_img/"+image_name);
			
			/*
			 * 验证扩展名jsp
			 */
			if(!image_name.toLowerCase().endsWith("jpg")){
				request.setAttribute("msg", "上传图片格式不对");
				request.setAttribute("categorys",categoryService.findAll() );
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				return;
			}
			//设置文件的保存路径
			String savePath = request.getServletContext().getRealPath("/book_img");
			File desFile = new File(savePath,image_name);
			file_image.write(desFile);
			/*
			 * 对图片尺寸的限制
			 */
			//desFile.getAbsolutePath()//取得该文件所在的绝对路径
			Image image = new ImageIcon(desFile.getAbsolutePath()).getImage();
			if(image.getWidth(null)>200 || image.getHeight(null)>200){
				desFile.delete();
				request.setAttribute("msg", "你上传的文件尺寸过大");
				request.setAttribute("categorys", categoryService.findAll());
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				return ;
			}
			
			bookService.add(book);

			request.getRequestDispatcher("/admin/AdminBookServlet?method=findAll").forward(request, response);
			
		} catch (Exception e) {
			throw new RuntimeException();
		}
		
		
	}

}
